<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>

      <el-breadcrumb-item>面经管理</el-breadcrumb-item>

    </el-breadcrumb>

    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>

          <el-button @click="optHandler('add')" icon="el-icon-plus" size="small" type="primary" round>
            添加面经
          </el-button>

        </div>

      </template>
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>

        <el-table-column prop="creator" label="作者"> </el-table-column>

        <el-table-column prop="likeCount" label="点赞"> </el-table-column>

        <el-table-column prop="views" label="浏览数"> </el-table-column>

        <el-table-column prop="createdAt" label="更新时间" width="200">
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <!-- <template slot-scope="scope">
            <div class="actions">
              <i @click="handleView(scope.$index, scope.row)" class="el-icon-view"></i>
              <i class="el-icon-edit-outline"></i>
              <i class="el-icon-delete"></i>
            </div>
          </template> -->
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <div class="actions">
              <i class="el-icon-view" @click="optHandler('view', scope.row)"></i>
              <i class="el-icon-edit-outline" @click="optHandler('edit', scope.row)"></i>
              <i class="el-icon-delete" @click="optHandler('del', scope.row)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination background @current-change="handleCurrentChange" :current-page="current" :page-size="pageSize"
        layout="prev, pager, next" :total="total">
      </el-pagination>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer :visible.sync="isShowDrawer" :before-close="handleClose" :title="drawerTitle" direction="rtl" size="50%">

      <div v-if="drawerType === 'view'" class="article-preview">
        <h5>{{ form.stem }}</h5>

        <div v-html="form.content"></div>
      </div>
      <el-form v-else label-width="80px" :model="form" :rules="rules" ref="form">
        <el-form-item label="标题" prop="stem">
          <el-input placeholder="输入面经标题" v-model="form.stem"></el-input>

        </el-form-item>

        <el-form-item label="内容" prop="content">
          <quill-editor v-model="form.content" @blur="$refs.form.validateField('content')"></quill-editor>
        </el-form-item>

        <el-form-item>
          <el-button type=" primary" @click="submit">确认</el-button>

          <el-button @click="handleClose">取消</el-button>

        </el-form-item>

      </el-form>


    </el-drawer>

  </div>

</template>

<script>
//导入axios请求接口
import {
  getArticleList, createArticle, removeArticle,
  getArticleDetail, updateArticle
} from '@/api/article'

// 导入富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'


export default {
  name: 'article-page',
  data() {
    return {
      current: 1,
      pageSize: 10,
      total: 0,
      list: [],//文章列表数据
      isShowDrawer: false,
      drawerType: '',//用于记录操作函数的类型
      form: {
        stem: '',//标题
        content: 'dddddd'//文本内容
      },
      rules: {
        stem: [{ required: true, message: '请输入面经标题', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入面经标题', trigger: 'blur' },
          { min: 20, message: "面经内容至少20个长度", trigger: "blur" },]
      },
    }
  },
  computed: {
    //计算属性，用于根据操作的不同切换抽屉的标题
    drawerTitle() {
      let title = '大标题'
      if (this.drawerType == 'add') title = '添加面经'
      if (this.drawerType == 'view') title = '面经预览'
      if (this.drawerType == 'edit') title = '修改面经'
      return title
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      const { data } = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      this.list = data.rows
      this.total = data.total
      console.log(data)
    },
    // handleView(index, row) {
    //   console.log(index, row);
    // },
    // 操作函数
    optHandler(type, row) {
      console.log(type, row);
      this.isShowDrawer = true
      this.drawerType = type
      // console.log('row：', row);
      // console.log('row.id', row?.id);
      if (type == 'del') {
        this.isShowDrawer = false//删除操作不需要打开抽屉
        // console.log('发送删除请求')
        this.del(row?.id)
      } else if (type == 'edit' || type == 'view') {
        // 回显数据
        this.openDrawer(row?.id)
      }

      // 重新渲染
      this.initData()
    },
    handleClose() {
      // 注意点: 由于公用的抽屉, 当预览时, 是没有表单的! 不能重置表单
      // 但是form的值还在, 会影响添加 => 需要手动重置一下
      // 关闭时将表单内容重置

      // 无论是哪种情况, 一律将form手动数据清零
      this.form = { stem: '', content: '' }

      if (this.drawerType !== 'view') {
        // add edit 调用 resetFields 在此处的作用: 重置校验状态
        this.$refs.form.resetFields()
      }

      // 确保关闭抽屉
      this.isShowDrawer = false
    },

    // 删除文章
    async del(id) {
      // 删除请求
      await removeArticle(id)
      // 添加成功的提示
      this.$message.success('删除成功')

      // 处理删除当前页的最后一条
      if (this.list.length === 1 && this.current > 1) {
        this.current--
      }
      // 重新渲染
      // this.initData()
    },
    //回显单个面经详情
    async openDrawer(id) {
      const res = await getArticleDetail(id)
      this.form = {
        ...res.data
      }
    },
    // 提交表单,添加文章
    // async submit() {
    //   try {
    //     console.log('提交表单')
    //     await this.$refs.form.validate()
    //     await createArticle(this.form)
    //     this.$message.success('添加成功')
    //     this.current = 1
    //     this.initData()
    //     this.handleClose()
    //     // 重置表单
    //     this.$refs.form.resetFields()
    //   } catch (e) {
    //     console.log(e)
    //   }
    // },
    async submit() {
      try {
        // 校验表单
        await this.$refs.form.validate()
        // 如何区分, 当前是 编辑 还是 添加
        if (this.drawerType === 'add') {
          // 发送请求
          await createArticle(this.form)
          // 添加提示 $message.success
          this.$message.success('添加成功')
        }
        if (this.drawerType === 'edit') {
          // 发送的是编辑的请求
          const { id, stem, content } = this.form
          await updateArticle({ id, stem, content })
          this.$message.success('修改成功')
        }
        // 无论是修改还是添加, 都会回到第一页, 重置页码
        this.current = 1
        // 重新渲染
        this.initData()
        // 关闭弹框
        this.handleClose()
      } catch (e) {
        console.log(e)
      }
    },

    handleCurrentChange(val) {
      // 处理当前页变化
      this.current = val
      this.initData()
    },

  },
  components: {
    quillEditor
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }

  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;

    >i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-breadcrumb {
  margin-top: 10px;
}

.el-form {
  padding-right: 40px;
}

.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}

.el-rate {
  padding: 10px 0;
}

.article-preview {
  padding: 0 40px 40px 40px;

  >h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
